package com.demo.springsecuritystudy.controller;

import io.jsonwebtoken.Jwts;
import io.micrometer.core.instrument.util.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.Authentication;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.nio.charset.StandardCharsets;

@RestController
@RequestMapping("/user")
public class TestController {

    @Value("${application.jwt.key:hello}")
    private String key;

    /**
     * 获取当前用户
     * @param authentication
     * @return
     */
    @GetMapping("/getCurrentUser")
    public Object getCurrentUser(Authentication authentication) {
        return authentication.getPrincipal();
    }

    @GetMapping("/parse")
    public Object parseToken(HttpServletRequest httpServletRequest) {
        Assert.isTrue(StringUtils.isNotEmpty(key), "reading configuration file application.jwt.key value is null");
        String header = httpServletRequest.getHeader("Authorization");
        String token = header.substring(header.indexOf("bearer") + 7);
        return Jwts.parser()
                .setSigningKey(key.getBytes(StandardCharsets.UTF_8))
                .parseClaimsJws(token).getBody();
    }
}
